/**
 * 从视频文件截取封面图
 * @param {File} videoFile - 视频文件
 * @param {Object} options - 配置项（可选）
 * @param {number} options.quality - 图片质量（0-1，默认 0.8）
 * @param {number} options.width - 封面图宽度（默认视频宽度）
 * @param {number} options.height - 封面图高度（默认视频高度）
 * @returns {Promise<Blob>} 封面图 Blob 对象
 */
export function getVideoCover(videoFile, options = {}) {
  const { quality = 0.8, width, height } = options;

  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.src = URL.createObjectURL(videoFile);
    video.crossOrigin = 'anonymous';

    video.addEventListener('loadeddata', () => {
      // 计算封面图宽高（保持视频宽高比）
      const videoWidth = video.videoWidth;
      const videoHeight = video.videoHeight;
      const coverWidth = width || videoWidth;
      const coverHeight = height || videoHeight;

      const canvas = document.createElement('canvas');
      canvas.width = coverWidth;
      canvas.height = coverHeight;

      const ctx = canvas.getContext('2d');
      // 绘制视频帧（居中裁剪，避免拉伸）
      ctx.drawImage(video, 0, 0, videoWidth, videoHeight, 0, 0, coverWidth, coverHeight);

      canvas.toBlob(
        (blob) => {
          URL.revokeObjectURL(video.src);
          resolve(blob);
        },
        'image/jpeg',
        quality
      );
    });

    video.addEventListener('error', (err) => {
      URL.revokeObjectURL(video.src);
      reject(err);
    });
  });
}
